using UnityEngine;
using System.Collections;
using LogicalComponent.util;
using LogicalComponent.rules.grid;

public class Slider : MonoBehaviour, MoveUtil.Mover {

    public Coordinate Position;
    public Coordinate Destination;

    private int step = 0;
    public float offset = 0f;
    public float speed = 15f;

    private MoveRulesUI moveRules;

    private Path path;
    private Coordinate nextTile;

    void Start()
    {
        moveRules = GameObject.FindGameObjectWithTag("game_manager").GetComponent<MoveRulesUI>();
        if (UiUtil.GetTile(Position) != null)
        {
            MoveUtil.Teleport(Position, this.transform);
        }
        Vector3 temp = new Vector3(this.transform.position.x,
                                   this.transform.position.y + offset,
                                   this.transform.position.z);
        this.transform.position = temp;
        this.Reset();
    }

    private void Reset()
    {
        step = 1;
        this.path = null;
    }

    public void DoMove(float timePassed)
    {
        if(Destination == Position && this.path == null)
        {
            this.Reset();
            return;
        }
        UseMoveTowards();
    }

    public void SetDestination(Coordinate c)
    {
        Destination = c;
        if(this.path != null)
        {
            this.Reset();
            step = 0;
            SearchAlgorithm search = new AStarSearch(
                this.moveRules.RuleSet, this.nextTile, this.Destination);
            search.DoSearch();
            this.path = search.GetPathTo(this.Destination);
            // this.path.InsertCoordinate(1, nextTile);
        }
        else
        {
            nextTile = null;
            this.Reset();
            SearchAlgorithm search = new AStarSearch(
                this.moveRules.RuleSet, this.Position, this.Destination);
            search.DoSearch();
            this.path = search.GetPathTo(this.Destination);
        }
    }

    private void UseMoveTowards()
    {
        step = MoveUtil.MoveAlong(this.path, step, this.transform, speed, Time.deltaTime);
        if(step < this.path.Length) this.nextTile = this.path.GetCoordinate(step);
        if (step >= 1)
        {
            this.Position = this.path.GetCoordinate(step - 1);
        }
    }
}
